package com.songqintuan.common.util;

import java.util.ArrayList;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import com.songqintuan.common.constant.GlobalConstants;


public final class ValidatorUtil {
	public ValidatorUtil(){
	}
	public static boolean isWhitespace (String s) {
		String  whitespace = " \t\n\r";
		int i;
		for (i = 0; i < s.length(); i++)
		{
			char c = s.charAt(i);
		    if (whitespace.indexOf(c) >= 0)
			{
		    	return true;
			}
		 }
		 return false;
	}
	protected static boolean isCharsInBag (String s, String bag) {
		int i;
		for (i = 0; i < s.length(); i++)
		{
			char c = s.charAt(i);
			if (bag.indexOf(c) == -1) return false;
		}
		return true;
	}
	protected static char isCharsInBagEx (String s, String bag) {
	    StringBuffer sbuffer=new StringBuffer(s);
        char c=' ',q;
        for (int i = 0; i < sbuffer.length(); i++)
        {
        	q = sbuffer.charAt(i);
        	if (bag.indexOf(q)>-1) {
        		c=q;
        		return c;
        	}
        }
        return c;
    }
	public static boolean isEmpty(String s)
	{
		return ((null == s) || (s.length()==0));
	}
	protected final boolean isEnglish(String s)
    {
    	if(isEmpty(s))
    	{
    		return false;
    	}
    	for(int i=0;i<s.length();i++)
    	{
    		char c=s.charAt(i);
    		if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='_')
    		{
    			continue;
    		}
    		else
    		{
    			return false;
    		}
    	}
    	return true;
    }
	public static void EmptyValidatorForInput(List<String> errorMessages, String value, String paramOfDispaly) {
		// TODO Auto-generated method stub
		FacesMessage message;
		if(isEmpty(value)){
			message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "value.empty.input.error.message", FacesMessage.SEVERITY_ERROR,(null == paramOfDispaly?"":"" + paramOfDispaly + ""));
			errorMessages.add(message.getDetail());
		}
	}
	public static void EmptyValidatorForSelect(List<String> errorMessages, String value, String paramOfDispaly) {
		// TODO Auto-generated method stub
		FacesMessage message;
		if(isEmpty(value)){
			message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "value.empty.select.error.message", FacesMessage.SEVERITY_ERROR,(null == paramOfDispaly?"":"" + paramOfDispaly  + ""));
			errorMessages.add(message.getDetail());
		}
	}
	
	public static void WhitespaceValidator(List<String> errorMessages, String value, String paramOfDispaly){
		FacesMessage message;
		if (null != value && !"".equals(value)) {
			if (isWhitespace(value)) {
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.blank.error.message", FacesMessage.SEVERITY_ERROR,(null == paramOfDispaly?"":"" + paramOfDispaly  + ""));
				errorMessages.add(message.getDetail());
			}
		}
	}
	
	public static void IntegerValidator(List<String> errorMessages, String value, String paramOfDispaly){
		FacesMessage message;
		if (null != value && !"".equals(value)) {
			if (!isInteger(value)) {
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.not.integer.error.message", FacesMessage.SEVERITY_ERROR,(null == paramOfDispaly?"":"" + paramOfDispaly  + ""));
				errorMessages.add(message.getDetail());
			}
		}
	}
	public static void addressValidate(List<String> errorMessages, String label, String address) {
		// TODO Auto-generated method stub
		char errorChar;
		String badChar = "><,[]{}?/+=|\\'\":;~!#$%()`";
		label = (null == label)?"":label;
		FacesMessage message;
		if(!isEmpty(address)){
			if ( isWhitespace(address) )
			{
				
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.blank.error.message", FacesMessage.SEVERITY_ERROR,label);
				errorMessages.add(message.getDetail());
			}

			errorChar = isCharsInBagEx( address, badChar);
	    	if (errorChar!= ' ' )
			{
		    	message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.error.message", FacesMessage.SEVERITY_ERROR,label,String.valueOf(errorChar));
		    	errorMessages.add(message.getDetail());
			}

		}
	}
	public static void emailValidate(List<String> errorMessages, String label, String email) {
		// TODO Auto-generated method stub
		FacesMessage message;
		label = (null == label)?"":label;
		if(!isEmpty(email)){
			if (email.length()<6)
		 	{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "email.length.error.message", FacesMessage.SEVERITY_ERROR, label, email.length());
				errorMessages.add(message.getDetail());
		    }
			if (email.length()>100){
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "email.length.error.message", FacesMessage.SEVERITY_ERROR, label, email.length());
				errorMessages.add(message.getDetail());
		 	}
			if ( isWhitespace(email) )
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.blank.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
			}
			int pos1 = email.indexOf("@");
			int pos2 = email.indexOf(".");
			int pos3 = email.lastIndexOf("@");
			int pos4 = email.lastIndexOf(".");
			if ((pos1 <= 0)||(pos1 ==email.length())||(pos2 <= 0)||(pos2 == email.length()))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.invalidate.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
				
			}else if( (pos1 == pos2 - 1) || (pos1 == pos2 + 1)
				  || ( pos1 != pos3 )  //find two @
				  || ( pos4 < pos3 ) ) //. should behind the '@'
				{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.invalidate.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
				}
			if ( !isCharsInBag( email, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_@"))
			{
				
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "email.char.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
				
			}

		}
	}
	
	public static void faxValidate(List<String> errorMessages, String label, String fax){
		// TODO Auto-generated method stub
		String badChar = "><[]{}?/+=|\\'\":~!@#$%^&`";
		//Validate the user name
		FacesMessage message;
		label = (null == label)?"":label;
		if(!isEmpty(fax))
		{   
			if ( isCharsInBag( fax, badChar))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.bad.error.message", FacesMessage.SEVERITY_ERROR,label,badChar);
				errorMessages.add(message.getDetail());
				
			}
			//check user length
			
			if(!isCharsInBag (fax, "0123456789-(),;+"))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.must.message", FacesMessage.SEVERITY_ERROR,label,"0123456789-(),;+");
				errorMessages.add(message.getDetail());
			}
		}

	}
	public static void imageValidate(List<String> errorMessages, String label, String imageName)
		{
		// TODO Auto-generated method stub
		FacesMessage message;
		label = (null == label)?"":label;
		if(!isEmpty(imageName))
			{  
			if (imageName.length()<=4)
		 	{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "image.length.error.message", FacesMessage.SEVERITY_ERROR, label, imageName.length());
				errorMessages.add(message.getDetail());
		    }
			if (imageName.length()>50){
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "image.length.error.message", FacesMessage.SEVERITY_ERROR, label, imageName.length());
				errorMessages.add(message.getDetail());
		 	}
			if ( isWhitespace(imageName) )
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.blank.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
			}
			int pos1 = imageName.lastIndexOf(".");
			if ((pos1 <= 0)||(pos1 ==imageName.length()))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.invalidate.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
				
			}else {
				
				String suffixStr= imageName.substring(pos1 + 1);
				if (!("jpg".equals(suffixStr.toLowerCase()) || "jpeg".equals(suffixStr.toLowerCase())|| "gif".equals(suffixStr.toLowerCase()))) {
					message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.invalidate.error.message", FacesMessage.SEVERITY_ERROR, label);
					errorMessages.add(message.getDetail());
				}
			}
			if ( !isCharsInBag( imageName, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_"))
			{
				
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.invalidate.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
				
			}
		}

	}
	public static void mobileValidate(List<String> errorMessages, String label, String mobile)
	{
		// TODO Auto-generated method stub
		String badChar = "><[]{}?/+=|\\'\":~!@#$%^&`";
		label = (null == label)?"":label;
		FacesMessage message;
		if(!isEmpty(mobile))
		{	
			if ( isCharsInBag( mobile, badChar))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.bad.error.message", FacesMessage.SEVERITY_ERROR,label,badChar);
				errorMessages.add(message.getDetail());
			}
			//check user length
			
			if(!isCharsInBag (mobile, "0123456789-(),;+"))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.must.message", FacesMessage.SEVERITY_ERROR,label,"0123456789-(),;+");
				errorMessages.add(message.getDetail());
			}
		}
	}
	
	public static void nameValidate(List<String> errorMessages, String label, String name)
	{
		// TODO Auto-generated method stub
		char errorChar;
		String badChar = "><,[]{}?/+=|\\'\":;~!#$%()`";
		label = (null == label)?"":label;
		FacesMessage message;
		if(!isEmpty(name)){
			if ( isWhitespace(name) )
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.blank.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
			}

			errorChar = isCharsInBagEx( name, badChar);
	    	if (errorChar!= ' ' )
	    	{
			
	    		message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.error.message", FacesMessage.SEVERITY_ERROR, label, String.valueOf(errorChar));
	    		errorMessages.add(message.getDetail());
	    	}
		}
	}
	public static void passwordValidate(List<String> errorMessages, String label, String password)
	{
		// TODO Auto-generated method stub
		FacesMessage message;
		if (null == password) {
			message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "password.required.error.message", FacesMessage.SEVERITY_ERROR, password.length());
			errorMessages.add(message.getDetail());
		}else {
        
			if (password.length()<6 || password.length()==0)
		 	{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "password.length.error.message", FacesMessage.SEVERITY_ERROR, password.length());
				errorMessages.add(message.getDetail());
		    }
			if (password.length()>30){
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "password.length.error.message", FacesMessage.SEVERITY_ERROR, password.length());
				errorMessages.add(message.getDetail());
		 	}
			if ( isWhitespace(password) )
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "password.blank.error.message", FacesMessage.SEVERITY_ERROR, password.length());
				errorMessages.add(message.getDetail());
			}
			if ( !isCharsInBag( password, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "password.char.error.message", FacesMessage.SEVERITY_ERROR);
				errorMessages.add(message.getDetail());
			}
		}

	}
	public static void phoneValidate(List<String> errorMessages, String label, String phone)
	{
		// TODO Auto-generated method stub
		String badChar = "><[]{}?/+=|\\'\":~!@#$%^&`";
		//Validate the user name
		FacesMessage message;
		label = (null == label)?"":label;
		if(!isEmpty(phone))
		{   
			
			if ( isCharsInBag( phone, badChar))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.bad.error.message", FacesMessage.SEVERITY_ERROR,label,badChar);
				errorMessages.add(message.getDetail());
				
			}
			//check user length
			
			if(!isCharsInBag (phone, "0123456789-(),;+"))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.must.message", FacesMessage.SEVERITY_ERROR,label,"0123456789-(),;+");
				errorMessages.add(message.getDetail());
			}
		}
	}
	
	public static void urlValidate(List<String> errorMessages, String label, String url)
	{
		// TODO Auto-generated method stub
		String webdomainregex = "http://([^/]+)/*";
		
		FacesMessage message;
		label = (null == label)?"":label;
		if(!isEmpty(url)){
			boolean matchFlag = Match(webdomainregex, url);
			if (!matchFlag)
		 	{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "url.validator.error.message", FacesMessage.SEVERITY_ERROR, label);
				errorMessages.add(message.getDetail());
		    }
		}
	}
	
	public static boolean Match(String regexstr, String str) {
		  Pattern regex = Pattern.compile(regexstr,Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
		  Matcher matcher = regex.matcher(str);
		  return matcher.matches();
		 }
	public static boolean isInteger(String sample){
        char[] charArray=sample.toCharArray();
        int index=0;
        if(charArray[0]=='-')
        	index=1;
        for(;index<charArray.length;index++)
        	if(!Character.isDigit(charArray[index]))
        		return false;
        return true;
	}

	public static boolean isFloat(String sample){
        int dot=0;
        char[] charArray=sample.toCharArray();
        int index=0;
        if(charArray[0]=='-') {
        	index=1;
        }
        for(;index<charArray.length;index++){
        	if(!Character.isDigit(charArray[index])&&charArray[index]!='.'){
        		return false; 
            }
            if(charArray[index]=='.'){
            	dot++;
            }
        }
        if(dot<2) {
        	return true;
        } else {
        	return false;
        }
	}


}
